import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
const routes = [
  {
    path: '/',
    redirect: 'login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginPage.vue')
  },
  {
    path: '/findPassword',
    name: 'findPassword',
    component: () => import('../views/FindPasswordPage.vue')
  },
  {
    path: '/fullScreen',
    name: 'fullScreen',
    component: () => import('../views/ScreenPage.vue')
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/IndexPage.vue'),
    redirect: 'screen',
    children: [
      {
        path: '/screen',
        name: 'screen',
        component: () => import('../views/ScreenPage.vue')
      },
      {
        path: '/userManage',
        name: 'userManage',
        meta: {
          requireRole: 'admin'
        },
        component: () => import('../views/UserManagePage.vue')
      },
      {
        path: '/recordManage',
        name: 'recordManage',
        component: () => import('../views/RecordManagePage.vue')
      },
      {
        path: '/riskRecordManage',
        name: 'riskRecordManage',
        component: () => import('../views/RiskRecordManagePage.vue')
      },
      {
        path: '/pipelineManage',
        name: 'pipelineManage',
        component: () => import('../views/PipelineManagePage.vue')
      },
      {
        path: '/stationManage',
        name: 'stationManage',
        component: () => import('../views/StationManagePage.vue')
      },
      {
        path: '/statistic',
        name: 'statistic',
        component: () => import('../views/StatisticPage.vue')
      },
      {
        path: '/personalCenter',
        name: 'personalCenter',
        component: () => import('../views/PersonalCenterPage.vue')
      },
      {
        path: '/config',
        name: 'config',
        meta: {
          requireRole: 'admin'
        },
        component: () => import('../views/ConfigPage.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const whiteList = ['/login', '/findPassword']

router.beforeEach((to, from, next) => {
  // 最近已登录过 免登录
  if (to.path === '/login' && from.path === '/' && localStorage.getItem('token')) {
    next('/index')
    return
  }
  // 不需要登录的路由
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  const userJson = localStorage.getItem('user')
  // 未登录
  if (!localStorage.getItem('token')) {
    next('/')
    return
  }
  const user = JSON.parse(userJson)
  // 需要权限
  if (to.meta.requireRole && to.meta.requireRole !== user.role) {
    ElMessage.error('权限不足')
    next(false)
  } else {
    next()
  }
})

export default router
